package com.sl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sl.entity.Result;
import com.sl.entity.StatusCode;
import com.sl.util.SMSUtils;
import com.sl.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("$/validateCode")
public class SMSController {

       // @Autowired
       // private RedisTemplate redisTemplate;

        @PostMapping("/telephone")
        public Result send4Order(@RequestBody String data, HttpServletRequest request){
            log.info("阿里爸爸发送信息data>>>>" + data);
            JSONObject jsonObject = JSONObject.parseObject(data);
            String telephone = jsonObject.getString("telephone");
            log.info("telephone>>>>" + telephone);
            // 生成短信验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            try{
                // 调用三方发送短信
                SMSUtils.sendShortMessage(telephone,code.toString());
            }catch(Exception e){
                e.printStackTrace();
                return new Result(false, StatusCode.ERROR,"阿里验证码发送失败");
            }
            log.info("阿里发送的手机验证码为："+code);
            // 把验证码缓存到 session
            HttpSession session= request.getSession();
            session.setAttribute("telephoneCode",code);
            session.setMaxInactiveInterval(5*60);
            // 把验证码缓存到redis
           // redisTemplate.expire(telephone,5*60, TimeUnit.SECONDS);
            return new Result(true,StatusCode.OK,"阿里验证码发送成功");
        }
}
